import React, { useEffect, useRef, useState, useMemo } from 'react';
import { notification, Spin, Modal, Form, Input, Cascader, Upload, message, AutoComplete, Select, Button, Table, InputNumber } from 'antd'
import { InboxOutlined } from '@ant-design/icons';
import { baseURL } from 'src/service/interceptors'

import {
    getMenu,
    updateFood,
    getResturantDetail,
    getMenuById
} from 'src/api/getData'

const Option = Select.Option

function UploadModal(props) {

    const {
        info = {},
        onOk,
        onCancel
    } = props;
    const [categorys, setCategorys] = useState()
    const [form] = Form.useForm()
    const [addform] = Form.useForm()
    const [fileList, setFileList] = useState([]);
    const [uploaded, setUploaded] = useState(false)
    const [loading, setLoading] = useState(true);
    const [specs, setSpecs] = useState([]);
    const [menus, setMenus] = useState([]);
    const [visible, setVisible] = useState(false);

    useEffect(() => {
        try {
            const specs = info.specfoods.map(item => {
                return {
                    specs: item.specs_name,
                    packing_fee: item.packing_fee,
                    price: item.price
                }
            })
            setSpecs(specs)
        } catch (error) {

        }
    }, [info])

    useEffect(() => {
        getMenuAsync()
    }, [])

    async function getMenuAsync() {
        try {
            const { restaurant_id } = info
            setLoading(true)
            const res = await getMenu({ restaurant_id, allMenu: true });
            setLoading(false)
            const menus = res.data.map((item, index) => {
                return {
                    name: item.name,
                    id: item.id,
                }
            })
            setMenus(menus)
        } catch (err) {
            console.log('获取食品种类失败', err);
        }
    }



    const normFile = (e) => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }

    async function handleOk() {
        try {
            const values = await form.validateFields()
            const { description, image_path, name, new_category_id } = values;
            setLoading(true)
            const res = await updateFood({
                ...info,
                name,
                description,
                new_category_id,
                image_path: image_path[0].response.data,
                specs
            })

            setLoading(false)
            if (res.code === 0) {
                message.success('更新店铺信息成功')
                onOk(values)
            }
        } catch (error) {
            console.error(error)
        }
    }

    function handelCancel() {
        onCancel && onCancel()
    }

    function deleteSpecs(index) {
        const specsNew = [...specs]
        specsNew.splice(index, 1);
        setSpecs(specsNew)
    }

    const maxsize = 2; //2M

    const uploadOption = {
        name: 'file',
        action: `${baseURL}v1/addimg/shop`,
        size: maxsize, //unit M
        accept: "image/jpeg,image/png",
        multiple: false,
        listType: "picture",
        showUploadList: {
            showRemoveIcon: true,
            removeIcon: " x ",
        },
        showUploadList: false,
        onChange(info) {

            setFileList([info.file]);
            const status = info.file.status;
            info.fileList.forEach(item => {
                item.thumbUrl = '';
            });
            if (status === 'uploading') {
                console.log(info.file, info.fileList);
                setUploaded(true)
            }
            if (status === "removed") {
                setUploaded(false);
                setFileList([])
            }
            if (status === 'done') {
                console.log(`${info.file.name} file uploaded successfully.`);
                setUploaded(true)
            }
            if (status === 'error') {
                notification.error({
                    message: "上传文件失败，请重试"
                });
                setUploaded(false)
            }
        },
        beforeUpload(file) {
            return new Promise((resolve, reject) => {

                if (file.type !== 'image/jpeg') {
                    notification.error({
                        message: "导入格式不正确",
                        duration: 5
                    });
                    return reject(false);
                }

                if (file.size / 1024 > maxsize * 1024) {
                    notification.error({
                        message: "导入文件不能超过" + maxsize + `M`,
                        duration: 5
                    });
                    return reject(false);
                }

                return resolve(true);
            });
        },
        fileList
    }


    return <div>
        <Modal
            title='修改食品信息'
            visible
            onOk={handleOk}
            onCancel={handelCancel}
            confirmLoading={loading}
            destroyOnClose
        >
            <Spin spinning={loading}>
                <Form
                    form={form}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name='name'
                        label="食品名称"
                        initialValue={info.name}
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <Input autoComplete="off" placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        name='description'
                        label="食品介绍"
                        initialValue={info.description}
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <Input autoComplete="off" placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        name='new_category_id'
                        label="食品分类"
                        initialValue={info.category_id}
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <Select>
                            {
                                menus.map((item) => {
                                    return <Option value={item.id} key={item.id}>{item.name}</Option>
                                })
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label="食品图片"
                        name="image_path"
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                        initialValue={[
                            {
                                response: {
                                    data: info.image_path
                                }
                            }
                        ]}
                        rules={[{ required: true, message: '请上传食品图片!' }]}
                    >
                        <Upload.Dragger
                            {...uploadOption}
                        >
                            {
                                fileList[0]?.response?.data ? <img src={`${baseURL}img/${fileList[0].response.data}`} /> :
                                    info.image_path ? <img src={`${baseURL}img/${info.image_path}`} /> :
                                        <>
                                            <p className="ant-upload-drag-icon">
                                                <InboxOutlined />
                                            </p>
                                            <p className="ant-upload-text">Click or drag file to this area to upload</p>
                                            <p className="ant-upload-hint">Support for a single or bulk upload.</p>
                                        </>
                            }
                        </Upload.Dragger>
                    </Form.Item>
                    <Form.Item noStyle>
                        <Table
                            columns={[
                                {
                                    title: '规格',
                                    dataIndex: 'specs'
                                },
                                {
                                    title: '包装费',
                                    dataIndex: 'packing_fee'
                                },
                                {
                                    title: '价格',
                                    dataIndex: 'price'
                                },
                                {
                                    title: '操作',
                                    dataIndex: 'action',
                                    render(text, record, index) {
                                        return <div>
                                            <Button
                                                onClick={() => deleteSpecs(index)}
                                                type="primary"
                                                danger
                                            >删除</Button>
                                        </div>
                                    }
                                },
                            ]}
                            dataSource={specs}
                            pagination={false}
                        />
                        <Button type="primary" onClick={() => setVisible(true)}>添加规格</Button>
                    </Form.Item>
                </Form>
            </Spin>
        </Modal>
        {
            visible && <Modal
                title="添加规格"
                visible
                onOk={async function () {
                    try {
                        const values = await addform.validateFields();
                        setSpecs([...specs, values])
                        setVisible(false)
                    } catch (error) {

                    }
                }}
                onCancel={function () {
                    setVisible(false)
                }}
            >
                <Form
                    form={addform}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name='specs'
                        label="规格"
                        initialValue=''
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <Input autoComplete="off" placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        name='packing_fee'
                        label="包装费"
                        initialValue={0}
                    >
                        <InputNumber min={0} max={100} placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        name='price'
                        label="价格"
                        initialValue={20}
                    >
                        <InputNumber min={0} max={10000} placeholder='请输入' />
                    </Form.Item>
                </Form>
            </Modal>
        }
    </div>
}

export default UploadModal